<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-form :inline="true" :model="listQuery" ref="listQuery">
        <el-form-item label=""  prop="roleName">
          <el-input @keyup.enter.native="searchFilter"  style="width: 200px;" class="filter-item" placeholder="角色名称" v-model="listQuery.roleName">
          </el-input>
        </el-form-item>
        <el-form-item label=""  prop="status">
          <el-select clearable style="width: 100px" class="filter-item" v-model="listQuery.status" placeholder="状态">
            <el-option
              v-for="item in statusArray"
              :label="item.value"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="searchFilter">搜索</el-button>
        <el-button class="filter-item" type="primary" v-waves  @click="resetForm('listQuery')">重置</el-button>
        <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="save" >添加</el-button>
      </el-form>
    </div>

    <el-table :data="tableData" v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row
              :default-sort = "{prop: 'createTime', order: 'descending'}">
      <el-table-column align="center" label='ID' width="95">
        <template slot-scope="scope">
          {{scope.$index+1}}
        </template>
      </el-table-column>
      <el-table-column label="角色名" sortable width="120" align="center" prop="roleName">
        <template slot-scope="scope">
          <span>{{scope.row.roleName}}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色编码" sortable width="120" align="center" prop="roleCode">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.id === '1'" :type="scope.row.roleCode">{{scope.row.roleCode}}</el-tag>
          <span v-else>{{scope.row.roleCode}}</span>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" sortable label="状态" width="110" align="center" prop="status">
        <template slot-scope="scope">
          <span>{{scope.row.status | statusFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" sortable prop="creator" label="创建人" width="120">
        <template slot-scope="scope">
          <span>{{scope.row.creator}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" sortable prop="createTime" label="创建时间" width="180">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span>{{scope.row.createTime}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center"sortable prop="updater" label="修改人" width="120">
        <template slot-scope="scope">
          <span>{{scope.row.updater}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" sortable prop="updateTime" label="修改时间" width="180">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span>{{scope.row.updateTime}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="350" class-name="small-padding">
        <template slot-scope="scope">
          <el-button type="primary" v-if="scope.row.status === '0' && scope.row.id !== '1'" size="mini" @click="enable(scope.row)">启用</el-button>
          <el-button type="primary" v-if="scope.row.status === '1' && scope.row.id !== '1'" size="mini" @click="disable(scope.row)">禁用</el-button>
          <el-button type="primary" v-if="scope.row.id !== '1'" size="mini" @click="edit(scope.row)">修改</el-button>
          <el-button type="primary" v-if="scope.row.id !== '1'" size="mini" @click="bindUser(scope.row)">绑定用户</el-button>
          <el-button type="danger" v-if="scope.row.id !== '1'" size="mini" @click="deleteRole(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.pageNum"
                     :page-sizes="[10,20,30, 50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <!--新增模态框-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="role" label-position="left" label-width="80px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="角色名" prop="roleName">
          <el-input v-model.trim="role.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色编码"  prop="roleCode">
          <el-input v-model.trim="role.roleCode"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio v-model.trim="role.status" label="1">启用</el-radio>
          <el-radio v-model.trim="role.status" label="0">禁用</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="saveRoleData">确 定</el-button>
        <el-button v-else type="primary" @click="updateRole">确 定</el-button>
      </div>
    </el-dialog>
    <!--角色绑定用户模态框-->
    <el-dialog :visible.sync="bindUserDialogVisible">
      <template>
        <el-transfer
          filterable
          :filter-method="filterMethod"
          filter-placeholder="请输入城市拼音"
          :render-content="renderFunc"
          v-model="alreadyBindUser"
          :props="{
            key: 'id',
            label: 'realName'
          }"
          @change="handleChange"
          :titles="['未绑定用户', '已绑定用户']"
          :button-texts="['到左边', '到右边']"
          :format="{
            noChecked: '${total}',
            hasChecked: '${checked}/${total}'
          }"
          :data="notBindUser">
        </el-transfer>
      </template>
    </el-dialog>
  </div>
</template>

<script>
  import { getListPage, deleteRole, enableRole, disableRole, modifyRole, saveRole, checkRoleName, getBindUserList } from '@/api/role'
  import waves from '@/directive/waves' // 水波纹指令
  import { isValidRolename, isValidRoleCode } from '@/utils/validate'
  export default {
    name: 'complexTable',
    directives: {
      waves
    },
    data() {
      const validateRoleName = (rule, value, callback) => {
        if (!isValidRolename(value)) {
          callback(new Error('角色名格式不正确'))
        } else {
          const param = {}
          param.roleName = value
          if (this.dialogStatus === 'update') {
            param.roleId = this.role.id
          }
          checkRoleName(param).then(response => {
            if (response) {
              callback(new Error('角色名已存在'))
            } else {
              callback()
            }
          })
        }
      }
      const validateRoleCode = (rule, value, callback) => {
        if (!isValidRoleCode(value)) {
          callback(new Error('角色编码格式不合法'))
        } else {
          callback()
        }
      }
      return {
        notBindUser: [],
        alreadyBindUser: [],
        renderFunc(h, option) {
          return <span>{ option.realName } - { option.cellPhone }</span>
        },
        filterMethod(query, item) {
          return item.realName.indexOf(query) > -1
        },
        tableData: null,
        listLoading: true,
        total: 0,
        listQuery: {
          pageNum: 1,
          pageSize: 20,
          roleName: '',
          status: ''
        },
        statusArray: [
          {
            code: '1',
            value: '启用'
          },
          {
            code: '0',
            value: '禁用'
          }
        ],
        dialogFormVisible: false,
        bindUserDialogVisible: false,
        dialogStatus: '',
        textMap: {
          update: '修改',
          create: '新增'
        },
        dialogPvVisible: false,
        downloadLoading: false,
        role: {
          id: '',
          roleName: '',
          roleCode: '',
          status: '1'
        },
        rules: {
          roleName: [
            { required: true, message: '角色名不能为空', trigger: 'blur' },
            { min: 2, max: 20, message: '角色名长度为2到20个字符', trigger: 'blur' },
            { validator: validateRoleName, trigger: 'blur' }
          ],
          roleCode: [
            { required: true, message: '角色编号不能为空', trigger: 'blur' },
            { min: 2, max: 20, message: '请正确填写姓名,支持2-20个汉字', trigger: 'blur' },
            { validator: validateRoleCode, trigger: 'blur' }
          ]
        }
      }
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          1: '启用',
          0: '禁用'
        }
        return statusMap[status]
      }
    },
    created() {
      this.fetchData()
    },
    methods: {
      fetchData() {
        this.listLoading = true
        getListPage(this.listQuery).then(response => {
          this.tableData = response.list
          this.total = response.total
          this.listLoading = false
        })
      },
      handleSizeChange(val) {
        this.listQuery.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.listQuery.pageNum = val
        this.fetchData()
      },
      save() {
        this.resetRoleData()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      saveRoleData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            saveRole(this.role).then(response => {
              if (response === 1) {
                this.dialogFormVisible = false
                this.fetchData()
                this.$notify({
                  title: '成功',
                  message: '保存成功',
                  type: 'success',
                  duration: 2000
                })
              } else {
                this.$message.error(response.message)
              }
            })
          }
        })
      },
      resetRoleData() {
        this.role = {
          roleName: '',
          roleCode: '',
          status: '1'
        }
      },
      edit(row) {
        this.role = Object.assign({}, row)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateRole() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            modifyRole(this.role).then(response => {
              if (response === 1) {
                this.dialogFormVisible = false
                this.fetchData()
                this.$notify({
                  title: '成功',
                  message: '更新成功',
                  type: 'success',
                  duration: 2000
                })
              } else {
                this.$message.error(response.message)
              }
            })
          }
        })
      },
      deleteRole(row) {
        this.$confirm(`确定删除角色${row.roleName}吗？`, '删除提示', {
          cancelButtonText: '取消',
          confirmButtonText: '确定',
          type: 'warning'
        }).then(() => {
          deleteRole(row.id).then(response => {
            if (response === 1) {
              this.fetchData()
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            } else {
              this.$message.error(response.message)
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      searchFilter() {
        this.listQuery.pageNum = 1
        this.fetchData()
      },
      resetForm(form) {
        this.$refs[form].resetFields()
        this.fetchData()
      },
      enable(row) {
        this.$confirm(`确定启用角色${row.roleName}吗？`, '启用提示', {
          cancelButtonText: '取消',
          confirmButtonText: '确定',
          type: 'warning'
        }).then(() => {
          enableRole(row.id).then(response => {
            if (response === 1) {
              this.fetchData()
              this.$message({
                type: 'success',
                message: '启用成功!'
              })
            } else {
              this.$message.error(response.message)
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消启用'
          })
        })
      },
      disable(row) {
        this.$confirm(`确定禁用角色${row.roleName}吗？`, '禁用提示', {
          cancelButtonText: '取消',
          confirmButtonText: '确定',
          type: 'warning'
        }).then(() => {
          disableRole(row.id).then(response => {
            if (response === 1) {
              this.fetchData()
              this.$message({
                type: 'success',
                message: '禁用成功!'
              })
            } else {
              this.$message.error(response.message)
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消禁用'
          })
        })
      },
      bindUser(row) {
        console.log(row)
        this.bindUserDialogVisible = true
        this.listLoading = true
        getBindUserList(row.id).then(response => {
          this.notBindUser = response.notBindUserList
          this.alreadyBindUser = response.alreadyBindUserIds
          this.listLoading = false
        })
      },
      handleChange(value, direction, movedKeys) {
        console.log(value, direction, movedKeys)
      }
    }
  }
</script>
